
import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sciolto/POJO/Song.dart';
import 'package:sciolto/UI/MusicPage.dart';
import 'package:sciolto/UI/feelingPage.dart';
import 'package:sciolto/UI/main_page.dart';
import 'package:sciolto/api/Common_api.dart';
import 'package:sciolto/api/music.dart';
import 'package:sciolto/util/setting.dart';
import 'package:sciolto/widget/custom_route.dart';
import 'package:sciolto/widget/custom_widget.dart';

class HomePage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin{

  Song _song;
  double _value;

  final _pages = [MainPage(), FeelingPage()];
  int _index;
  Size _size;
  double _x , _y;

  /// 动画
  AnimationController _buttonController;
  Animation _buttonFromCenterToBottomAnimation;
  Animation<double> _buttonZoomInAnimation;
  var _buttonBgColorAnimation;


  @override
  void initState() {
    super.initState();
    _index = 0;
    _initAnimation();

    Music().initAllResource();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        Future.delayed(Duration(seconds: 4), (){
          _buttonController.forward();
        });
      });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _size ??= CommonApi.initParameter(context);
    _x ??= _size.width / 420;
    _y ??= _size.height / 800;
    final musicState = Provider.of<Music>(context);
    _song = musicState.song ?? Song.withError();
    _value = musicState.value;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    Music().dispose();
    _buttonController.dispose();
  }

  /// --------------------------------------------------------------------------
  /// 私有方法区
  /// --------------------------------------------------------------------------

  /// 初始化动画组件
  void _initAnimation(){
    /// 动画控制器
    _buttonController = AnimationController(
        duration: Duration(milliseconds: 1500),
        vsync: this
    );

    /// 从中间至底部的动画
    _buttonFromCenterToBottomAnimation = AlignmentTween(
        begin: Alignment.center,
        end: Alignment.bottomCenter
    ).animate(
        CurvedAnimation(
            parent: _buttonController,
            curve: Interval(
                0.0,
                0.2,
                curve: Curves.easeIn
            )
        )
    )..addListener(() {setState(() {

    });});

    /// 按钮从大到小的动画
    _buttonZoomInAnimation = Tween(
      begin: 800.0,
      end: 60.0,
    ).animate(
        CurvedAnimation(
            parent: _buttonController,
            curve: Curves.bounceOut
        )
    )..addListener(() {setState(() {

    });});

    /// 颜色变化的动画
    _buttonBgColorAnimation = ColorTween(
        begin: Colors.grey[50],
        end: Colors.blue[50]
    ).animate(
        CurvedAnimation(
            parent: _buttonController,
            curve: Curves.ease
        )
    )..addListener(() {setState(() {

    });});
  }

  /// --------------------------------------------------------------------------
  /// 点击事件区
  /// --------------------------------------------------------------------------

  ///
  /// TODO 点击播放列表图标时调用
  void _onTappingPlayList(){
    CustomWidget.showPlayList(context, _size, _x, _y);
  }

  ///
  /// TODO 点击信息框，跳转至歌曲界面
  void _onTappingInfoBar(){
    Navigator.of(context).push(
      CustomRoute(MusicPage(), CustomRoute.BOTTOM_TO_TOP, 300)
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: _buttonFromCenterToBottomAnimation.value,
      children: [
        SizedBox(
          width: _size.width,
          height: _size.height,
          child: SingleChildScrollView(
            child: SizedBox(
              width: _size.width,
              height: _size.height,
              child: Scaffold(
                body: _pages[_index],
                bottomNavigationBar: Container(
                  width: _size.width,
                  height: 140 * _y,
                  alignment: Alignment.center,
                  child:Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                          flex: 2,
                          // TODO 信息栏
                          child: _infoBar()
                      ),
                      Expanded(
                          flex: 2,
                          child: Container(
                              color: Setting.themeColor,
                          )
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
        Material(
          color: Colors.transparent,
          type: MaterialType.transparency,
          child: Container(
            width: _buttonZoomInAnimation.value > _size.width
                ? _size.width : _buttonZoomInAnimation.value > 140 * _y
                ? _buttonZoomInAnimation.value : 140 * _y,
            height: _buttonZoomInAnimation.value > _size.height
                ? _size.height : _buttonZoomInAnimation.value > 140 * _y
                ? _buttonZoomInAnimation.value : 140 * _y,
            color: Colors.transparent,
            child: Stack(
              alignment: Alignment.center,
              children: [
                SizedBox(
                    width: _buttonZoomInAnimation.value > _size.width
                        ? _size.width : _buttonZoomInAnimation.value > 100 * _y
                        ? _buttonZoomInAnimation.value : 100 * _y,
                    height: _buttonZoomInAnimation.value > _size.height
                        ? _size.height : _buttonZoomInAnimation.value > 100 * _y
                        ? _buttonZoomInAnimation.value : 100 * _y,
                    child: Container(
                      decoration: BoxDecoration(
                          color: _buttonBgColorAnimation.value,
                          shape: _buttonZoomInAnimation.value > 500.0
                              ? BoxShape.rectangle : BoxShape.circle
                      ),
                      child: _buttonZoomInAnimation.value > 500
                          ? Center(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                height: 200 * _y,
                                width: 350 * _y,
                                child: Image(
                                  image: AssetImage("images/SCIOLTO.png"),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.symmetric(vertical: 20 * _y),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    FlutterLogo(),
                                    SizedBox(width: 10 * _y,),
                                    Text("produced by Flutter",
                                      style: TextStyle(color: Colors.grey[400]),
                                    )
                                  ],
                                ),
                              )
                            ],
                          )
                      ) : Container(),
                    )
                ),
                SizedBox(
                    width: _buttonZoomInAnimation.value > 500.0
                        ? 0.0 : _buttonZoomInAnimation.value > 100 * _y
                        ? _buttonZoomInAnimation.value : 100 * _y,
                    height: _buttonZoomInAnimation.value > 500.0
                        ? 0.0 : _buttonZoomInAnimation.value > 100 * _y
                        ? _buttonZoomInAnimation.value : 100 * _y,
                    child: CircularProgressIndicator(
                      value: _value,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.blueGrey),
                    )
                ),
                SizedBox(
                    width: _buttonZoomInAnimation.value > 500.0
                        ? 0.0 : _buttonZoomInAnimation.value > 100 * _y
                        ? _buttonZoomInAnimation.value : 100 * _y,
                    height: _buttonZoomInAnimation.value > 500.0
                        ? 0.0 : _buttonZoomInAnimation.value > 100 * _y
                        ? _buttonZoomInAnimation.value : 100 * _y,
                    child: IconButton(
                      padding: EdgeInsets.all(0),
                      icon: Image(
                        color: Colors.cyan,
                        image: AssetImage(
                            Music().isPlaying ? "images/pause.png" : "images/play.png"
                        ),
                      ),
                      onPressed: (){
                        setState(() {
                          Music().isPlaying ? Music().pause() : Music().play();
                          // isPlaying = !isPlaying;
                        });
                      },
                    )
                ),
              ],
            ),
          ),
        )
      ],
    );
  }

  /// ----------------------------------------------
  /// widget
  /// ----------------------------------------------

  /// 信息条
  Widget _infoBar(){
    return GestureDetector(
      onTap: _onTappingInfoBar,
      child: Container(
        color: Colors.white,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(
              flex : 3,
              child: Container(
                color: Setting.backgroundColorForLight,
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 10 * _x),
                child: Text(
                  // TODO: 获取当前正在听的歌
                  "正在收听 : ${_song.songName}",
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Setting.itemHighLight
                  ),
                ),
              ),
            ),
            Spacer(
              flex: 2,
            ),
            Expanded(
              flex : 3,
              child: Container(
                  color: Setting.backgroundColorForLight,
                  alignment: Alignment.centerRight,
                  padding: EdgeInsets.symmetric(horizontal: 20 * _x, vertical: 15 * _y),
                  child: GestureDetector(
                    onTap: _onTappingPlayList,
                    child: Image(
                      color: Setting.itemHighLight,
                      image: AssetImage("images/playList.png"),
                    ),
                  )
              ),
            ),
          ],
        ),
      )
    );
  }

  /// 底部跳转按钮
  // Widget _bottomNavigator(){
  //   return Row(
  //     crossAxisAlignment: CrossAxisAlignment.center,
  //     children: [
  //       Expanded(
  //         flex: 1,
  //         child: GestureDetector(
  //           // TODO: 点击事件
  //             onTap: (){
  //               setState(() {
  //                 _index = 0;
  //               });
  //             },
  //             child:Container(
  //                 alignment: Alignment.center,
  //                 padding: EdgeInsets.symmetric(vertical: 10 * _y),
  //                 child: Column(
  //                   mainAxisAlignment: MainAxisAlignment.center,
  //                   crossAxisAlignment: CrossAxisAlignment.center,
  //                   children: [
  //                     Expanded(
  //                       flex: 1,
  //                       child: Image(
  //                         color: _index == 0 ?
  //                         Setting.itemHighLight :
  //                         Setting.itemResignFocus,
  //                         image: AssetImage("images/listen.png"),
  //                       ),
  //                     ),
  //                     Text(
  //                       "个人主页",
  //                       style: TextStyle(
  //                         color: _index == 0 ?
  //                         Setting.itemHighLight :
  //                         Setting.itemResignFocus,
  //                       ),
  //                     )
  //                   ],
  //                 )
  //             )
  //         ),
  //       ),
  //       Spacer(flex: 1,),
  //       Expanded(
  //         flex: 1,
  //         child: GestureDetector(
  //           // TODO: 点击事件
  //             onTap: (){
  //               setState(() {
  //                 _index = 1;
  //               });
  //             },
  //             child:Container(
  //                 alignment: Alignment.center,
  //                 padding: EdgeInsets.symmetric(vertical: 10 * _y),
  //                 child: Column(
  //                   mainAxisAlignment: MainAxisAlignment.center,
  //                   crossAxisAlignment: CrossAxisAlignment.center,
  //                   children: [
  //                     Expanded(
  //                       flex: 1,
  //                       child: Image(
  //                         color: _index == 1 ?
  //                         Setting.itemHighLight :
  //                         Setting.itemResignFocus,
  //                         image: AssetImage("images/notebooks.png"),
  //                       ),
  //                     ),
  //                     Text(
  //                       "感想",
  //                       style: TextStyle(
  //                         color: _index == 1 ?
  //                         Setting.itemHighLight :
  //                         Setting.itemResignFocus,
  //                       ),
  //                     )
  //                   ],
  //                 )
  //             )
  //         ),
  //       ),
  //     ],
  //   );
  // }

}